package net.lookyou.boot.demo.config.security.provider;

import net.lookyou.boot.demo.config.security.service.PhoneUserDetailsService;
import net.lookyou.boot.demo.config.security.token.PhoneAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 手机号码自定义认证器
 */
@Component
public class PhoneAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private PhoneUserDetailsService phoneUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneAuthenticationToken phoneAuthenticationToken = (PhoneAuthenticationToken) authentication;
        String phone = (String) phoneAuthenticationToken.getPrincipal();
        if(StringUtils.isBlank(phone)){
            throw new BadCredentialsException("手机号码不能为空");
        }

        UserDetails userDetails = phoneUserDetailsService.loadUserByUsername(phone);
        //安全起见密码不要返回
        return  new PhoneAuthenticationToken(phone,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        /**
         * providerManager会遍历所有
         * SecurityConfig中注册的provider集合
         * 根据此方法返回true或false来决定由哪个provider
         * 去校验请求过来的authentication
         */
        return (PhoneAuthenticationToken.class.isAssignableFrom(aClass));

    }
}
